// utils/request.js
import { getBaseUrl } from './address'
import { token, message } from './index'

// 请求拦截
const request = (config) => {
  // 深拷贝配置
  const options = JSON.parse(JSON.stringify(config))
  
  // 添加基础URL
  const baseUrl = getBaseUrl()
  options.url = options.url.startsWith('http') ? options.url : baseUrl + options.url
  
  // 添加认证头
  if (token.hasToken()) {
    options.headers = options.headers || {}
    options.headers['Authorization'] = `Bearer ${token.getToken()}`
  }
  
  // 返回请求promise
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        handleResponse(res, options, resolve, reject)
      },
      fail: (err) => {
        handleError(err, options, resolve, reject)
      }
    })
  })
}

// 处理响应
const handleResponse = (res, options, resolve, reject) => {
  const { statusCode, data } = res
  
  // 根据状态码处理
  if (statusCode === 200) {
    if (data.code === 200) {
      // 业务成功
      resolve(data)
    } else if (data.code === 401) {
      // 未授权，处理令牌刷新
      handleTokenRefresh(options, resolve, reject)
    } else {
      // 特殊处理token使用情况接口
      if (options.url.includes('/user/daily-token-usage')) {
        resolve(getDefaultTokenUsage())
        return
      }
      // 业务失败
      message.error(data.message || '请求失败')
      reject(new Error(data.message || '请求失败'))
    }
  } else if (statusCode === 401) {
    // 未授权，处理令牌刷新
    handleTokenRefresh(options, resolve, reject)
  } else {
    // 特殊处理token使用情况接口
    if (options.url.includes('/user/daily-token-usage')) {
      resolve(getDefaultTokenUsage())
      return
    }
    // 其他错误
    message.error(`请求失败(${statusCode}): ${data?.message || '未知错误'}`)
    reject(new Error(data?.message || `请求失败: ${statusCode}`))
  }
}

// 处理错误
const handleError = (err, options, resolve, reject) => {
  // 特殊处理token使用情况接口
  if (options.url.includes('/user/daily-token-usage')) {
    resolve(getDefaultTokenUsage())
    return
  }
  
  message.error('网络连接失败，请检查网络')
  reject(err)
}

// 处理令牌刷新
const handleTokenRefresh = async (options, resolve, reject) => {
  try {
    // 获取刷新令牌
    const refreshTokenValue = token.getRefreshToken()
    if (!refreshTokenValue) {
      throw new Error('刷新令牌不存在')
    }
    
    // 调用刷新接口
    const refreshRes = await uni.request({
      url: getBaseUrl() + '/auth/refresh-token',
      method: 'POST',
      data: { refreshToken: refreshTokenValue },
      header: { 'Content-Type': 'application/json' }
    })
    
    if (refreshRes.statusCode === 200 && refreshRes.data.code === 200) {
      // 更新令牌
      const refreshData = refreshRes.data.data
      token.setToken(refreshData.token)
      token.setRefreshToken(refreshData.refreshToken)
      
      // 重新发送原始请求
      options.headers = options.headers || {}
      options.headers['Authorization'] = `Bearer ${token.getToken()}`
      
      // 重新调用请求
      request(options).then(resolve).catch(reject)
    } else {
      // 刷新失败，跳转登录
      message.error('登录已过期，请重新登录')
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/login/account-login' })
      }, 1500)
      reject(new Error('登录已过期'))
    }
  } catch (err) {
    console.error('刷新Token失败', err)
    message.error('登录已过期，请重新登录')
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/login/account-login' })
    }, 1500)
    reject(err)
  }
}

// 获取默认的token使用情况数据
const getDefaultTokenUsage = () => {
  return {
    code: 200,
    data: {
      dailyUsed: 0,
      limit: 10000,
      isDefault: true
    },
    success: true
  }
}

// 导出请求方法
export default {
  request,
  get: (url, data, headers) => request({ url, method: 'GET', data, headers }),
  post: (url, data, headers) => request({ url, method: 'POST', data, headers }),
  put: (url, data, headers) => request({ url, method: 'PUT', data, headers }),
  delete: (url, data, headers) => request({ url, method: 'DELETE', data, headers })
}